<template>
  <s-layout title="超级星期天">
    <view class="lottery-container">
      <div class="lottery_box">
        <image
          class="bgi"
          src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/Prize_draw/merchant_SuperWeekend.png"
          mode="widthFix"
        ></image>
        <!-- 顶部奖金展示 -->
        <view
          class="my"
          @click="sheep.$router.go('/pages/tuangou/business_lottery_result_week')"
        >
          我的抽奖记录
        </view>
        <view class="topriqi">{{ state.selectedWeek?.sub_title }}</view>
        <view class="btnwq">
          <view class="btnwq-item" @tap="toggleDateRange">往期奖池</view>
          <!-- <picker
            @change="onPickerChange"
            :value="selectedIndex"
            :range="weeks"
            class="pickercls"
            range-key="sub_title"
          >
            往期奖池
          </picker> -->
        </view>
        <view class="topprice">￥</view>
        <view class="toppricenum">{{ state.selectedWeek?.price }}</view>
        <!-- 转盘抢红包区域 -->
        <view class="lottery-grid">
          <view style="display: flex;align-items: center;justify-content: center;padding-top: 100rpx;">
            <view class="zhuanpan">
              <view
                class="point"
                v-for="item in 9"
                :key="item"
              ></view>
              <view
                class="content"
                :style="{'background-image':groupbg,transform:'rotateZ('+rotate+'deg)',transition: 'transform '+second+'s'}"
              >
                <template
                  v-for="(item,index) in display_prizes"
                  :key="index"
                >
                  <!-- 每个奖品格子旋转相应角度 -->
                  <view
                    class="item"
                    :style="{transform: 'rotateZ('+index*(360/8)+'deg)'}"
                  >

                    <!-- <view class="img">
									<image :src="item.image" mode="aspectFit"></image>
								</view> -->
                    <view class="name">{{item.name}}</view>
                  </view>
                </template>
              </view>
              <view class="arrow"></view>
            </view>
          </view>
        </view>
      </div>
      <!-- 抢红包按钮 -->
      <view class="cjbtn">
        <template v-if="dateflag">
          <template v-if="payflag">
            <template v-if="!prizeflag">
              <view
                class="cjtext"
                @click="start"
              >
                点击立即抢红包
              </view>
            </template>
            <template v-else>
              <view class="cjtext">
                感谢您的参与
              </view>
            </template>
          </template>
          <template v-else>
            <view class="cjtext">
              未有抢红包资格
            </view>
          </template>
        </template>
        <template v-else>
          <view class="cjsettime">
            <view style="margin-top: 15rpx; font-size: 24rpx;">获奖时间每周日20点到22点</view>
            <view
              style="margin-top: 5rpx;"
              class="settime"
            >
              <image
                class="bell"
                src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250326/21de12bf28340254bcfa1cae215d7a74.png"
              ></image>
              <view style="color: #FA5151;">{{ days }}天{{ hours }}时{{ minutes }}分{{ seconds }}秒</view>
            </view>
          </view>
        </template>

      </view>
      <!-- 中奖名单 -->
      <view class="textzj">
        {{ dateflag ? '本期中奖名单' : '上期中奖名单' }}
      </view>
      <view
        class="textwq"
        @click="sheep.$router.go('/pages/tuangou/business_lottery_list_week')"
      >
        往期名单
        <view class="jt" />
      </view>
      <view class="mingdan">
        <view 
          style="text-align: center;color: #888; padding-top: 20rpx;" 
          v-if="messages.length === 0"
        >暂无中奖人员</view>
        <swiper
          :autoplay="true"
          :interval="1000"
          :duration="3000"
          :circular="true"
          :vertical="true"
          :disable-touch="true"
          style="height: 170rpx;"
          :slides-per-view="1"
          :display-multiple-items="3"
          ref="mySwiperRef"
        >
          <swiper-item v-for="(message, index) in desensitizedMobile">
            <view class="swiper-item">
              <view class="item">
                {{ message.user.nickname }}
              </view>
              <view
                class="item"
                style="width: 155rpx;"
              >
                {{ message.phonetm }}
              </view>
              <view
                class="item"
                style="width: 80rpx;"
              >
                {{ message?.product_name }}
              </view>
              <view
                class="item"
                style="width: 255rpx;"
              >
                {{ message.create_time }}
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>
      <!-- 中奖弹窗 -->
      <view
        class="prize-popup"
        v-if="show_result"
      >
        <view class="popup-content">
          <view class="popup-title">抢红包结果</view>
          <view class="popup-prize">{{ win_prize?.product_name }}</view>
          <view
            class="popup-btn"
            @click="close_popup(win_prize?.product_name)"
          >确定</view>
        </view>
      </view>
      <!-- pop -->

      <su-popup
        type="bottom"
        @change="state.optionShow = $event.show"
        :show="state.optionShow"
        backgroundColor="#fff"
        :round="15"
        maskBackgroundColor="rgba(0, 0, 0, 0.8)"
        class="option-box-popup"
      >
        <view class="popup-content option-box">
          <view class="popup-header">
            <text class="cancel" @tap="handleStageClose">关闭</text>
            <text class="confirm" @tap="handleStageConfirm">选择</text>
          </view>
          <view class="picker">
            <picker-view  
              class="picker-view" 
              :value="stageVal" 
              @change="handleStageChange"
            >
              <picker-view-column>
                <view class="item prize-item-name" v-for="item in weeks" :key="item.id">{{ item.title }}</view>
              </picker-view-column>
            </picker-view>
          </view>
        </view>
      </su-popup>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue';
import { onLoad, onUnload, onHide, onShow } from '@dcloudio/uni-app';
import sheep from '@/sheep';

// 当前时间是否是周日20~22点， 如果是轮询中奖名单，如果不是轮询红包金额
const dateflag = ref(false)
// 用户是否拥有抢红包资格
const payflag = ref(false)
// 用户是否已经抽过奖
const prizeflag = ref(true)

// 状态定义
const state = reactive({
  prize_list: [],
  optionShow: false,
  selectedWeek: {}
});

const current_index = ref(-1);
const win_prize = ref({});


// 中奖弹窗
const show_result = ref(false);

const groupbg = ref('');
const color1 = ref('#ffed85');
const color2 = ref('#ffe020');
const rotate = ref(0); // 当前旋转角度
const second = ref(4); // 旋转动画持续时间
const isactive = ref(false); // 是否正在抽奖
const activeIndex = ref(0); // 当前抽奖的奖品索引，记录当前指针位置，用于计算旋转

// 用户手机号脱敏处理
const desensitizedMobile = computed(() => {
  return messages.value.map((item, index) => ({
    ...item,
    phonetm: item.user.mobile ? item.user.mobile.slice(0, 3) + '****' + item.user.mobile.slice(-4) : '空',
  }));
});

const toggleDateRange = () => {
  state.optionShow = true
}

const handleStageClose = () => {
  state.optionShow = false
}

const handleStageConfirm = () => {
  state.selectedWeek = Object.keys(state.selectedWeek).length === 0 ? weeks[0] : state.selectedWeek
  handleStageClose()
}


const handleStageChange = (e) => {
  const val = e.detail.value // index
  console.log(val[0])
  // 获取选中的周
  state.selectedWeek = weeks.value[val[0]]
  console.log(state.selectedWeek, 'selectedWeek')
}

// 获取开奖档期
const get_lotteryPeriods = async (flag) => {
  const res = await sheep.$api.prize_week.lotterysupplierDayPeriods();
  console.log('获取开奖档期&奖池金额',res)
  const { error, msg } = res
  if (error == 0) {
    weeks.value = res.data
    state.selectedWeek = weeks.value[0]
    get_lotteryPool()
    if (flag) {
      get_lotteryOpenLog()
    }
  } else {
    console.log('获取开奖档期失败: ', msg)
  }
};

// 获取奖池内奖品信息
const get_lotteryPool = async () => {
  const res = await sheep.$api.prize_week.lotterysupplierDayPool();
  console.log('获取奖池内奖品信息',res)
  const { error, msg } = res
  if (error == 0) {
    let prizelist = res.data
    res.data.forEach((item, index) => {
      if (item.name === '开始抢红包') {
        prizelist.splice(index, 1)
      }
    })
    console.log('获取奖池内奖品信息==========',prizelist)

    state.prize_list = prizelist
    if (state.prize_list.length < 8) {
      const dataToInsert = {
        id: null,
        image: "https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/PrizeDraw/1.png",
        name: "谢谢参与",
        point: "wallet",
        pool_id: null
      };
      const newArray = new Array(8 - state.prize_list.length).fill(dataToInsert);
      state.prize_list = state.prize_list.concat(newArray);
    }
  } else {
    console.log('获取奖池内奖品信息失败: ', msg)
  }
};

// 获取中奖人员名单
const get_lotteryOpenLog = async () => {
  // 商家中奖记录
  const res = await sheep.$api.prize_week.lotterysupplierDayopenLog({ id: weeks.value[selectedIndex.value]?.id });
  console.log('res数据获取中奖人员名单', res)
  const { error, msg } = res
  if (error == 0) {
    messages.value = res.data.data
  } else {
    console.log('获取中奖人员名单失败: ', msg)
  }
};


// 点击立即抢红包
const start = async () => {
  // 是否正在抽奖
  if (isactive.value)  return;  // 防止重复点击
  try {
    //  获取抢红包结果
    const res = await sheep.$api.prize_week.lotterysupplierDayapply();
    const { error, msg } = res
    if (error == 0) {
      console.log('res', res)
      console.log('state.prize_list', state.prize_list)
      // 找到中奖奖品的位置索引
      let n = state.prize_list.findIndex(item => item.id === res.data?.product_id);
      console.log('n',n)
      if (n == -1) {
        uni.showToast({
          title: '未找到对应奖品',
          icon: 'none'
        })
        return
      }
      isactive.value = true
      /**
       * @description 1800度(5圈) + 奖品位置的角度差
       * 1800度(5圈) + 奖品位置的角度差
       * 当前指向第0个奖品（activeIndex = 0），中奖奖品在第3个位置（n = 3）
       * 计算公式：1800 + (0 - 3) * 360 / 8 = 1800 - 135 = 1665
       * 旋转1665度后，指针指向第3个奖品
       */
      rotate.value += (1800 + (activeIndex.value - n) * 360 / 8)

      setTimeout(() => {
        activeIndex.value = n; // 中奖奖品索引
        prizeflag.value = true // 中奖标志
        isactive.value = false // 是否正在抽奖
        win_prize.value = res.data // 中奖奖品
        setTimeout(() => {
          show_result.value = true; // 中奖弹窗
        }, 100);
      }, second.value * 1000)
    } else {
      console.log('msg',msg)
      uni.showToast({
        title: msg,
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('Lottery error:', error);
    uni.showToast({
      title: '抽奖失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    isactive.value = false;
  }
}

// 初始化轮盘奖项背景颜色
const init = async () => {
  //绘制转盘奖项背景颜色
  let str = '';
  let num = 8;
  let deg = 360 / num;
  let colors = [];
  str += `conic-gradient(from ${-deg / 2}deg at 50% 50%,`;
  for (var i = 0; i < num; i++) {
    if (i % 2 == 0) {
      colors.push(`${color1.value} ${i * deg}deg,${color1.value} ${(i + 1) * deg}deg,${color2.value} ${(i + 1) * deg}deg`)
    } else {
      colors.push(`${color2.value} ${i * deg}deg,${color2.value} ${(i + 1) * deg}deg,${color1.value} ${(i + 1) * deg}deg`)
    }
  }
  str += colors.join(',')
  str += ')';
  groupbg.value = str
};

const messages = ref([]);

let scrollInterval;
let dataUpdateInterval;
let priceUpdateInterval;
const mySwiperRef = ref(null);

// 中奖人员更新的函数
const updateData = async () => {
  try {
    const res = await sheep.$api.prize_week.lotterysupplierDayopenLog({ id: weeks.value[0]?.id });

    messages.value.shift(); // 移除第一条消息
    messages.value.unshift(res.data.data[0])
  } catch (error) {
    console.log('更新中奖人员数据失败:',error)
  }
};

// 开始中奖数据更新的函数
const startDataUpdate = () => {
  dataUpdateInterval = setInterval(() => {
    updateData();
  }, 5000); // 每 5 秒更新一次数据，可根据实际情况调整
};

// 奖池金额更新
const updatePrice = async () => {
  const res = await sheep.$api.prize_week.lotterysupplierDayPeriods();
  console.log('奖池金额更新',res)
  const { error, msg } = res
  if (error == 0) {
    weeks.value = res.data
    state.selectedWeek = weeks.value[0]
  } else {
    console.log('奖池金额更新失败: ', msg)
  }
};

// 开始奖池金额更新
const startPriceUpdate = () => {
  priceUpdateInterval = setInterval(() => {
    updatePrice();
  }, 3000); // 每 5 秒更新一次数据，可根据实际情况调整
};


// 计算属性
const display_prizes = computed(() => {
  return state.prize_list.map((item, index) => ({
    ...item,
    is_center: item.name === '开始抢红包',
    original_index: index,
  }));
});

// 关闭弹窗
const close_popup = async (name) => {
  show_result.value = false;
  current_index.value = -1;

  if (name !== '谢谢惠顾') {
    await sheep.$store('user').getInfo();
    sheep.$router.go('/pages/tuangou/business_lottery_result_week');
  }
};

// 初始化总秒数为 7 天的秒数
const totalSeconds = ref(7 * 24 * 60 * 60);
// const totalSeconds = ref(7 * 24 * 60 * 60);
const days = ref(0);
const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);

let countdownInterval;
// 倒计时(到下一个周日的晚上19点)
const updateCountdown = () => {
  if (totalSeconds.value > 0) {
    // 每秒减少 totalSeconds.value 的值，并重新计算剩余的天数、小时数、分钟数和秒数
    totalSeconds.value--;
    days.value = Math.floor(totalSeconds.value / (24 * 60 * 60));
    const remainingSecondsAfterDays = totalSeconds.value % (24 * 60 * 60);
    hours.value = Math.floor(remainingSecondsAfterDays / (60 * 60));
    const remainingSecondsAfterHours = remainingSecondsAfterDays % (60 * 60);
    minutes.value = Math.floor(remainingSecondsAfterHours / 60);
    seconds.value = remainingSecondsAfterHours % 60;
  } else {
    // 倒计时结束，开启定时刷新中奖用户，到了抽奖的时间了
    clearInterval(countdownInterval);
    clearInterval(priceUpdateInterval);
    dateflag.value = true
    selectedIndex.value = 1
    // 开启定时刷新中奖用户
    startDataUpdate();
  }
};

// 周范围数组
const weeks = ref([{
  id: 1,
  title: '2025-04-07',
  sub_title: '2025-04-07',
  price: 100
}, {
  id: 2,
  title: '2025-04-08',
  sub_title: '2025-04-08',
  price: 100
}]);

// 当前选择的周索引
const selectedIndex = ref(0);

// 处理选择器变化事件
const onPickerChange = (e) => {
  selectedIndex.value = e.detail.value;
  clearInterval(priceUpdateInterval);
};

// 生命周期
onLoad(async () => {
  // 初始化轮盘
  init()
  // 获取奖池档期
  await get_lotteryPeriods(true)

  const res = await sheep.$api.prize_week.lotterysupplierDay();
  const { error, msg } = res
  if (error == 0) {
    const status = res.data?.status
    if (status === 'have') {
      payflag.value = true
      prizeflag.value = false
    }
    if (status === 'no') {
      payflag.value = false
      prizeflag.value = false
    }
    if (status === 'used') {
      payflag.value = true
      prizeflag.value = true
    }

    let begintime = res.data?.periods?.join_begin_time
    let endtime = res.data?.periods?.join_end_time
    const now = new Date();
    const startDateTime = new Date(begintime);
    const endDateTime = new Date(endtime);

    // 调用函数进行判断
    const result = now >= startDateTime && now <= endDateTime

    if (result) {
      dateflag.value = true;
      selectedIndex.value = 1
      // 开启定时刷新中奖用户
      startDataUpdate();
      return
    } else {
      dateflag.value = false;
      selectedIndex.value = 0
      // 开启定时刷新奖池金额
      startPriceUpdate()
    }
    // 计算下周日的日期
    const nextSunday = new Date(now);
    nextSunday.setDate(now.getDate() + (7 - now.getDay()));

    // 设置下周日晚上 20:00 的时间
    nextSunday.setHours(20, 0, 0, 0);

    // 计算时间差（以秒为单位）
    // const timeDiff = 20;
    const timeDiff = (nextSunday - now) / 1000;
    totalSeconds.value = timeDiff.toFixed(0)
    countdownInterval = setInterval(updateCountdown, 1000);
  } else {
    console.log('获取开奖档期失败: ', msg)
  }
  
});

onShow(async () => {
  console.log('onShow')
  await get_lotteryPeriods(true)
})

onHide(() => {
  // 清除所有定时器
  console.log('onHide 清除所有定时器')
  clearInterval(scrollInterval);
  clearInterval(dataUpdateInterval);
  clearInterval(countdownInterval);
  clearInterval(priceUpdateInterval);
});

onUnload(() => {
  clearInterval(scrollInterval);
  clearInterval(dataUpdateInterval);
  clearInterval(countdownInterval);
  clearInterval(priceUpdateInterval);
});
onUnmounted(() => {
  clearInterval(scrollInterval);
  clearInterval(dataUpdateInterval);
  clearInterval(countdownInterval);
  clearInterval(priceUpdateInterval);
});

</script>

<style lang="scss" scoped>
@import './style/business-lottery.scss';
</style>
